//
// Copyright (c) 2014 the ParticleEditor2D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include "DialIntEditor.h"
#include <QDial>
#include <QSpinBox>
#include <QVBoxLayout>

namespace Urho3D
{

DialIntEditor::DialIntEditor(const QString& text) :
    QGroupBox(text),
    lastDialValue_(0)
{
    QVBoxLayout* vBoxLayout = new QVBoxLayout();
    setLayout(vBoxLayout);

    dial_ = new QDial();
    
    dial_->setWrapping(true);
    dial_->setRange(0, 100);
    connect(dial_, SIGNAL(dialPressed()), this, SLOT(dialPressed()));
    connect(dial_, SIGNAL(valueChanged(int)), this, SLOT(dialValueChanged(int)));
    
    spinBox_ = new QSpinBox;
    vBoxLayout->addWidget(spinBox_, 1);
    vBoxLayout->addWidget(dial_);
    spinBox_->setAlignment(Qt::AlignHCenter);
    spinBox_->setButtonSymbols(QSpinBox::NoButtons);
    connect(spinBox_, SIGNAL(valueChanged(int)), this, SLOT(spinBoxValueChanged(int)));
}

DialIntEditor::~DialIntEditor()
{
}

void DialIntEditor::setValue(int value)
{
    spinBox_->setValue(value);
}

void DialIntEditor::setRange(int min, int max)
{
    spinBox_->setRange(min, max);
    
    int range = (max - min) / 3;
    if (range < 10)
        range = 10;
    dial_->setMaximum(range);
}

int DialIntEditor::value() const
{
    return (int)spinBox_->value();
}

void DialIntEditor::dialPressed()
{
    lastDialValue_ = dial_->value();
}

void DialIntEditor::dialValueChanged(int value)
{
    int delta = value - lastDialValue_;
    lastDialValue_ = value;

    int range = dial_->maximum();
    if (delta < -range / 2)
        delta += range;
    if (delta > range / 2)
        delta -= range;
    spinBox_->setValue(spinBox_->value() + delta);
}

void DialIntEditor::spinBoxValueChanged(int value)
{
    emit valueChanged(value);
}

}